/*
 * @Author: 烟浮
 * @Date: 2022-06-18 14:24:42
 * @LastEditTime: 2023-03-22 12:06:24
 * @LastEditors: 锦墨涵秋 275740441@qq.com
 * @FilePath: /ViteSsoIndex/ViteSsoIndex/src/service/request/index.ts
 */
import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { SlRequestInterceptors, slRequestConfit } from './types'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

const SHOW_LOADING = true

class SlRequest {
  instance: AxiosInstance
  interceptors?: SlRequestInterceptors
  loading?: LoadingInstance
  showLoading: boolean

  constructor(config: slRequestConfit) {
    // 创建 axios 实例
    this.instance = axios.create(config)

    // 保存基本信息
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? SHOW_LOADING

    /**
     * 使用拦截器
     * 1、从 config 中取出的拦截器对应的实例的拦截器
     */
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    /**
     * 2、添加所有的实例都有拦截器
     */
    this.instance.interceptors.request.use(
      (config) => {
        // console.log('所有的实例都有的拦截器: 请求成功拦截')
        if (this.showLoading) {
          this.loading = ElLoading.service({
            text: 'loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
        }
        return config
      },
      (err) => {
        // console.log('所有的实例都有的拦截器: 请求失败拦截')
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // console.log('所有的实例都有的拦截器: 响应成功拦截')
        this.loading?.close()

        const data = res.data
        if (data.returnCode === '-1001') {
          console.log('请求失败，错误信息')
        } else {
          return data
        }
      },
      (err) => {
        // console.log('所有的实例都有的拦截器: 响应失败拦截')
        return err
      }
    )
  }

  request<T = any>(config: slRequestConfit<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 1、单个请求对请求 config 的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      // 判断是否显示 loading
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 单个请求对数据的梳理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          // 将 showLoading 设置为 true, 这样不会影响下一个请求
          this.showLoading = SHOW_LOADING
          // 将结果返回出去
          resolve(res)
        })
        .catch((err) => {
          // 将 showLoading 设置为 true, 这样不会影响下一个请求
          this.showLoading = SHOW_LOADING
          reject(err)
          return err
        })
    })
  }

  get<T = any>(config: slRequestConfit<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T = any>(config: slRequestConfit<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  delete<T = any>(config: slRequestConfit<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T = any>(config: slRequestConfit<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default SlRequest
